package com.cskaoyan.service.promotion;

import com.cskaoyan.bean.promotion.Ad;
import com.cskaoyan.bean.promotion.AdExample;
import com.cskaoyan.mapper.AdMapper;
import com.cskaoyan.utils.DataUtils;
import com.cskaoyan.vo.promotion.AdListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @description:
 * @autyor:caicaicai
 */
@Service
public class AdServiceImpl implements AdService {

    @Autowired
    AdMapper adMapper;

    @Override
    public AdListVo query(Integer page, Integer limit, String sort, String order, String name, String content) {
        //分页(page当前页数， limit每页的条数）
        PageHelper.startPage(page, limit);
        //构造条件
        AdExample adExample = new AdExample();
        adExample.setOrderByClause(sort + " " + order);//按照条款排序（条件 升降序）
        AdExample.Criteria criteria = adExample.createCriteria();
        criteria.andDeletedEqualTo(false);//逻辑删除为false
        //条件查询
        if(name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        if(content != null && !"".equals(content)){
            criteria.andContentLike("%" + content + "%");
        }
        List<Ad> ads = adMapper.selectByExample(adExample);

        //分页
        //total != ads.size();
        //total是满足条件的所有的数据量 而不是当前limit

        //可以通过PageInfo获得分页信息
        //PageInfo其实是pagehelper给我们封装的一个类，里面有一些我们做分页表常用的属性
        PageInfo<Ad> adPageInfo = new PageInfo<>(ads);
        long total = adPageInfo.getTotal();//总的数据量 select count(*) 条件是byExample

        AdListVo adListVo = new AdListVo();
        adListVo.setItems(ads);
        adListVo.setTotal(total);
        return adListVo;
    }

    @Override
    public int update(Ad ad) {
        //int affectedRows = adMapper.updateByPrimaryKey(ad);
        int affectedRows = adMapper.updateByPrimaryKeySelective(ad);
        if(affectedRows == 1){
            return 200;
        }
        return 404;
    }

    @Override
    public Ad create(Ad ad) {
        Date nowDate = DataUtils.getCurrentTime();
        ad.setAddTime(nowDate);
        ad.setUpdateTime(nowDate);

        //插入数据后,主键被塞回输入映射的对象中
        adMapper.insertSelective(ad);
        return ad;
    }

    @Override
    public int delete(Ad ad) {
        //逻辑删除，即修改属性deleted=true
        ad.setDeleted(true);
        int affectedRows =adMapper.updateByPrimaryKeySelective(ad);
        if(affectedRows == 1){
            return 200;
        }
        return 404;
    }
}
